package com.qf.homework.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

//避免重复创建session
public class Batis01Util {
    /*public static SqlSession reSess() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = sqlSessionFactoryBuilder.build(resourceAsStream);
        SqlSession sqlSession = build.openSession();
        return sqlSession;
    }*/
    //获取sqlSession对象
    private static SqlSessionFactory sqlSessionFactory;
    //创建threadLocal该对象用于保存线程私有的数据
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    //静态代码块初始化
    static {
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = sqlSessionFactoryBuilder.build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static SqlSession getSqlSession(){
        //先检查当前线程是否获取过
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession!=null){
            return sqlSession;
        }
        //该方法每次调用都会创建一个sqlSession对象
        sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }
    public static void commit(){
        SqlSession sqlSession = getSqlSession();
        sqlSession.commit();
        closeSqlSession();
    }
    public static void closeSqlSession(){
        SqlSession sqlSession = getSqlSession();
        sqlSession.close();
    }
    public static void rollback(){
        SqlSession sqlSession = getSqlSession();
        sqlSession.rollback();
        closeSqlSession();
    }
    public static <T>T getMapper(Class<T> clazz){
        SqlSession sqlSession = getSqlSession();
        T mapper = sqlSession.getMapper(clazz);
        return mapper;
    }
}
